import request from '@/utils/request'

// ==================== 接口类型定义 ====================

/**
 * 评论图片接口
 */
export interface CommentImage {
  image_id: number
  image_url: string
  image_url_full: string
}

/**
 * 用户信息接口
 */
export interface UserInfo {
  user_id: number
  username: string
  avatar_url: string
}

/**
 * 评论详情接口
 */
export interface Comment {
  comment_id: number
  user: number
  user_info?: UserInfo
  goods: number
  order: number
  content: string
  rating: number
  images: CommentImage[]
  reply_content: string | null
  reply_time: string | null
  comment_time: string
}

/**
 * 创建评论请求参数接口
 */
export interface CreateCommentParams {
  goods: number // 商品ID（必填）
  order: number // 订单ID（必填）
  content: string // 评论内容（必填）
  rating: number // 评分 1-5星（必填）
  images?: File[] // 评论图片（可选）
}

/**
 * 创建评论响应接口
 */
export interface CreateCommentResponse {
  comment_id: number
  user: number
  user_info: UserInfo
  goods: number
  order: number
  content: string
  rating: number
  images: CommentImage[]
  reply_content: string | null
  reply_time: string | null
  comment_time: string
}

// ==================== API 服务 ====================

/**
 * 评论API服务
 */
export const commentsApi = {
  /**
   * 获取商品评论列表
   * GET /reviews/goods/{goods_id}/
   * @param goods_id - 商品ID
   */
  getGoodsComments(goods_id: number): Promise<Comment[]> {
    return request({
      url: `/reviews/goods/${goods_id}/`,
      method: 'get',
    }).then((response: any) => {
      // 处理分页格式的响应
      if (response && typeof response === 'object') {
        if (Array.isArray(response.results)) {
          return response.results
        } else if (Array.isArray(response)) {
          return response
        }
      }
      return []
    })
  },

  /**
   * 获取用户评论列表
   * GET /reviews/user/
   */
  getUserComments(): Promise<Comment[]> {
    return request({
      url: '/reviews/user/',
      method: 'get',
    }).then((response: any) => {
      // 处理分页格式的响应
      if (response && typeof response === 'object') {
        if (Array.isArray(response.results)) {
          return response.results
        } else if (Array.isArray(response)) {
          return response
        }
      }
      return []
    })
  },

  /**
   * 创建评论
   * POST /reviews/
   * @param params - 创建评论参数
   */
  createComment(params: CreateCommentParams): Promise<CreateCommentResponse> {
    const formData = new FormData()
    formData.append('goods', params.goods.toString())
    formData.append('order', params.order.toString())
    formData.append('content', params.content)
    formData.append('rating', params.rating.toString())

    // 添加图片文件
    if (params.images && params.images.length > 0) {
      params.images.forEach((image) => {
        formData.append('images', image)
      })
    }

    return request({
      url: '/reviews/',
      method: 'post',
      data: formData,
      headers: {
        'Content-Type': 'multipart/form-data',
      },
    })
  },

  /**
   * 删除评论
   * DELETE /reviews/{comment_id}/
   * @param comment_id - 评论ID
   */
  deleteComment(comment_id: number): Promise<void> {
    return request({
      url: `/reviews/${comment_id}/`,
      method: 'delete',
    })
  },
}

// ==================== 工具函数 ====================

/**
 * 格式化评论时间
 */
export const formatCommentTime = (timeString: string): string => {
  const date = new Date(timeString)
  const now = new Date()
  const diffTime = Math.abs(now.getTime() - date.getTime())
  const diffDays = Math.floor(diffTime / (1000 * 60 * 60 * 24))

  if (diffDays === 0) {
    // 今天
    return date.toLocaleTimeString('zh-CN', {
      hour: '2-digit',
      minute: '2-digit',
    })
  } else if (diffDays === 1) {
    // 昨天
    return (
      '昨天 ' +
      date.toLocaleTimeString('zh-CN', {
        hour: '2-digit',
        minute: '2-digit',
      })
    )
  } else if (diffDays < 7) {
    // 一周内
    return `${diffDays}天前`
  } else {
    // 更早
    return date.toLocaleDateString('zh-CN', {
      month: '2-digit',
      day: '2-digit',
    })
  }
}

// ==================== 默认导出 ====================

export default commentsApi
